package com.example.minzhengtong.ui

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.Gravity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.example.minzhengtong.Const
import com.example.minzhengtong.R
import com.example.minzhengtong.base.BaseA
import com.example.minzhengtong.data.HistoryBean
import com.example.minzhengtong.databinding.ActivitySocialInsuranceCBinding
import com.example.minzhengtong.utils.*
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView
import okhttp3.*
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

class SocialInsuranceC : BaseA() {

    companion object {
        fun enterThis(context: Context) {
            val intent = Intent(context, SocialInsuranceC::class.java)
            context.startActivity(intent)
        }
    }
    private lateinit var binding: ActivitySocialInsuranceCBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val viewManager = windowManager

//        windowManager

//        val  comm.android.view.WindowManager

//        val android.view.WindowManager.LayoutParams lp = window.attributes

//        window.attributes.verticalMargin = 50f;
//        window.decorView.layoutParams.height = window.decorView.layoutParams.height - 50
//        window.decorView.top = 50
////        window.attributes =
////        viewManager.addView(window.decorView,window.attributes)

//        ImmersionBar.with(this).statusBarDarkFont(false).
//        statusBarColor(R.color.black).init();


        binding = ActivitySocialInsuranceCBinding.inflate(layoutInflater)
        overridePendingTransition(0, 0)




        setContentView(binding.root)



        setToolBarVisiabale(false)
        ImmersionBar.with(this).titleBar(binding.titleBar).statusBarDarkFont(true).init()

//        initImmerBar(false, R.id.title_bar)
//
//
////        ImmersionBar.with(this).titleBar(binding.titleBar).statusBarDarkFont(true).init()
//
//
//        setToolBarVisiabale(false)

        // 显示状态栏
//        binding.webview.visibility = View.GONE
        initTab()
        initTime()
        initHint()
        initInfo()
    }



    private fun initInfo() {
        val showAccount = StringBuilder()
        LogUtil.d("展示账户${userBean!!.data!!.uzh!!}")
        showAccount.append(userBean!!.data!!.uzh!!.substring(0, 1))
        for (i in userBean!!.data!!.uzh!!.indices - 2) {
            showAccount.append("*")
        }
        if (showAccount.length > 3) {
            LogUtil.d("删除账户星号前$showAccount")
            showAccount.delete(showAccount.length - 2, showAccount.length)
            LogUtil.d("删除账户星号后$showAccount")
        }
        showAccount.append("${userBean!!.data!!.uzh!!.substring(userBean!!.data!!.uzh!!.length - 2)}")
        Log.d("TAG", "initInfo: "+userBean?.data)
        binding.name.text = "*${userBean?.data?.uname?.substring(1)}  (${userBean?.data?.account_institutions})"
        binding.money.text = userBean?.data?.zhye
        binding.money.setOnClickListener {
            startActivity(Intent(this@SocialInsuranceC, SocialInsuranceB::class.java))
        }
        Watermark.getInstance().show(baseContext, userBean!!.data!!.lxs, binding.containerContent)
    }

    private var tabTitle = mutableListOf("企业职工养老保险", "工伤保险", "失业保险")
    private var fragments = mutableListOf(
        SocialFG.newInstance(),
        SocialFG.newInstance(1),
        SocialFG.newInstance(2)
    )

    private fun initTab() {
        val navigator = CommonNavigator(baseContext)
        val navAdapter: CommonNavigatorAdapter = object : CommonNavigatorAdapter() {
            override fun getTitleView(context: Context?, index: Int): IPagerTitleView {
                val titleView = SimplePagerTitleView(baseContext)
                titleView.normalColor = resources.getColor(R.color.black)
                titleView.selectedColor = resources.getColor(R.color.blue045dd9)
                titleView.textSize = 15f
                titleView.text = tabTitle[index]
                titleView.setOnClickListener { binding.viewPager.currentItem = index }
//                titleView.width = WUtils.getScreenWidth(baseContext) / 3
                titleView.gravity = Gravity.CENTER
//                if (index == 0){
//                    titleView.setPadding(WUtils.dp2px(baseContext,25f),0,WUtils.dp2px(baseContext,15f),0)
//                    titleView.width = WUtils.getScreenWidth(baseContext) / 10 * 5
//                }else{
                titleView.setPadding(
                    WUtils.dp2px(baseContext, 15f),
                    0,
                    WUtils.dp2px(baseContext, 15f),
                    0
                )
//                    titleView.width = WUtils.getScreenWidth(baseContext) / 10 * 2
//                }
                return titleView
            }

            override fun getCount(): Int {
                return tabTitle.size
            }

            override fun getIndicator(context: Context?): IPagerIndicator {
                val indicator = LinePagerIndicator(baseContext)
                indicator.mode = LinePagerIndicator.MODE_WRAP_CONTENT
                indicator.lineHeight = 6f
//                indicator.mode = LinePagerIndicator.MODE_MATCH_EDGE
                indicator.setColors(resources.getColor(R.color.blue045dd9))
                return indicator
            }
        }
        navigator.adapter = navAdapter
        binding.viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                navAdapter.getTitleView(baseContext, position).onSelected(position, tabTitle.size)
                navAdapter.notifyDataSetChanged()
            }
        })
        binding.indicator.navigator = navigator
        ViewPagerHelper.bind(binding.indicator, binding.viewPager)
        binding.viewPager.adapter = object : FragmentPagerAdapter(supportFragmentManager) {
            override fun getItem(position: Int): Fragment {
                return fragments[position]
            }

            override fun getCount(): Int {
                return fragments.size
            }
        }
        binding.viewPager.offscreenPageLimit = fragments.size
    }

    private val dateFormat = SimpleDateFormat("yyyy-MM")

    private fun initTime() {
        val calendar = Calendar.getInstance()
        calendar.time = Date()
        calendar.add(Calendar.YEAR, -1)

        binding.start.text = dateFormat.format(calendar.time)
        binding.end.text = dateFormat.format(Date())

        detail(binding.start.text.toString(), binding.end.text.toString())

        binding.start.setOnClickListener {
            val pickerView = TimePickerBuilder(
                this
            ) { date, v ->
                binding.start.text = getTime(date)
                detail(binding.start.text.toString(), binding.end.text.toString())
            }.build()
            pickerView.show()
        }

        binding.end.setOnClickListener {
            val pickerView = TimePickerBuilder(
                this
            ) { date, v ->
                binding.end.text = getTime(date)
                detail(binding.start.text.toString(), binding.end.text.toString())
            }.build()
            pickerView.show()
        }

    }

    private fun getTime(date: Date): String? { //可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.time)
        return dateFormat.format(date)
    }

    private fun initHint() {
        val str1 = "若您有厦门社保，可查看"
        val str2 = "厦门社保>"
        val spannableString = SpannableString(str1 + str2)
        spannableString.setSpan(
            ForegroundColorSpan(resources.getColor(R.color.blue2f2fcf)),
            str1.length,
            (str1 + str2).length,
            SpannableString.SPAN_EXCLUSIVE_INCLUSIVE
        )
        binding.hint.text = spannableString
    }

    fun setTime(start: String, end: String) {
        binding.start.text = start
        binding.end.text = end
    }

    fun getStartTime(): String {
        return binding.start.text.toString()
    }

    fun getEndTime(): String {
        return binding.end.text.toString()
    }

    private fun detail(start: String, end: String) {
//        mData1.clear()
        val okHttpClient = OkHttpClient()
        val body: RequestBody = FormBody.Builder()
            .add("token", SpUtil.getInstance().getString(Const.TOKEN))
            .add("start", start)
            .add("end", end)
            .build()
        val request = Request.Builder()
            .url(Const.history)
            .post(body)
            .build()
        val call = okHttpClient.newCall(request)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                UIUtils.showToastSafely("网络连接失败")
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                val json = response.body()!!.string()
                LogUtil.d("获取列表数据$json")
                val bean = Gson().fromJson(json, HistoryBean::class.java)
                if (1 == bean.status) {
                    runOnUiThread {
                        binding.start.text = bean.data.start
                        binding.end.text = bean.data.end
//                        mData.addAll(bean.data.list)
//                        mAdapter.notifyDataSetChanged()
//                        if (mData.size == 0){
//                            showToast("该时间段内未查询到记录")
//                        }
                    }
                } else {
                    UIUtils.showToastSafely(bean.msg)
                }
            }
        })
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(0, 0)
    }
}